'use strict';

const Controller = require('egg').Controller;

const {saveFile} = require('./../../utils/fs-extend')

class ArticleController extends Controller {

  constructor(...props) {
    super(...props)
    //创建的规则
    const createValidateRule = { 
      user_id: 'string', functionality_id: 'string', tag_ids: 'array', headline: 'string',
      outline: 'string', cover_url: 'string', authority: 'string', content: 'string',
      access_token: 'string'
    }
    this.createValidateRule = createValidateRule
  }
  
  //@GET 
  async index() {
    const { ctx, service } = this;
    const { Response, ResponseError, query } = ctx
    const res = new Response() //作为响应
    try {
      let articles = null
      if(Object.keys(query).length === 0) { //获取所有
        articles = await service.article.findAll()
        res.data = { articles }
      }else { //条件匹配
        const { search } = query
        if(search) res.data = await service.article.findAllByKeyWord(search)
      }
      res.message = '获取数据成功'
    }catch(e) {
      console.log(e)
      res.status = ctx.STATUS.ERROR;
			res.message = e;
    }
    ctx.body = res
  }
  
  //@POST
  async create() {
    const { ctx, service } = this;
    const { Response, ResponseError, request: { body }, session } = ctx
    const res = new Response()
		try {
      ctx.validate(this.createValidateRule, body)
      const { user_id, functionality_id, tag_ids, headline, outline, cover_url, authority, content, access_token } = body;
      if(session.user_id != user_id) {
        throw new ResponseError('用户没有登入信息，没有权限')
      }

      let user = await service.user.find(user_id)
      if(user.access_token != access_token) { //令牌验证
        throw new ResponseError('用户令牌无法识别，没有权限')
      }

      const upload_path_id = 2 //文章保存路径id
      const {value: uploadPath} = await service.uploadPath.find(upload_path_id)
      const fieldname = headline //字段名
      const suffixP = '.md' //后缀
      const filename = ctx.randomFileName(headline + suffixP) //文件名
      saveFile(uploadPath, filename , content) //写入文件
      const file = await service.file.create({
        upload_path_id, mime_type: 'text/markdown', filename,
        encoding: '7bit', fieldname
      })
      //验证成功，进行注册
      await service.article.create({
        user_id, file_id: file.id, functionality_id, tag_ids: JSON.stringify(tag_ids), headline,
        outline, cover_url, authority
      })
      res.message = '文章发表成功'
		} catch (e) {
      console.log(e)
			res.status = ctx.STATUS.ERROR;
			res.message = e;
		}
		ctx.body = res;
  }
  // "fileInfo": {
  //   "fileName": "1599128267072_md.md",
  //   "uploadPath": "",
  //   "encoding": "7bit",
  //   "mime": "text/markdown",
  //   "fieldname": "md",
  //   "fullPath": "1599128267072_md.md"
  // }
}

module.exports = ArticleController;
